package com.tanhua.server.interceptor;

import cn.hutool.core.util.StrUtil;
import com.tanhua.common.pojo.User;
import com.tanhua.common.utils.NoAuthorization;
import com.tanhua.common.utils.UserThreadLocal;
import com.tanhua.server.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class UserTokenInterceptor implements HandlerInterceptor {
    @Autowired
    private UserService userService;

    /**
     * 将User对象放入线程
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 校验是不是对控制器的请求
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        // 判断是否包含@NoAuthorization注解,如果包含,直接放行
        if (((HandlerMethod) handler).hasMethodAnnotation(NoAuthorization.class)) {
            return true;
        }

        // 从请求头中获取token
        String token = request.getHeader("Authorization");
        if (StrUtil.isNotEmpty(token)) {
            User user = userService.queryUserByToken(token);
            if (null != user) {
                // token有效,将User对象放入线程
                UserThreadLocal.set(user);
                return true;
            }
        }

        // token无效,响应状态吗401(无权限)
        response.setStatus(401);

        return false;
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 将线程上的User对象删除
        UserThreadLocal.remove();
    }
}
